package com.resou.reader.bookdetail;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.ms.square.android.expandabletextview.ExpandableTextView;
import com.resou.reader.MainActivity;
import com.resou.reader.R;
import com.resou.reader.api.entry.BaseComment;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.TypeBean;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.bookdetail.comment.CommentListActivity;
import com.resou.reader.bookdetail.comment.detail.CommentDetailActivity;
import com.resou.reader.bookdetail.comment.release.ReleaseCommentActivity;
import com.resou.reader.bookdetail.listener.OnCommentOnclickListener;
import com.resou.reader.bookdetail.view.BookDetailCommentView;
import com.resou.reader.bookdetail.view.BookDetailRecomView;
import com.resou.reader.commom.Constant;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.vipcenter.vipCenter.VipCenter;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.TextUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.view.Loading;
import com.resou.reader.view.NetErrorFragment;
import com.resou.reader.view.StarRatingBar;
import com.resou.reader.view.UnShelfFragment;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.umeng.socialize.bean.SHARE_MEDIA.*;

/**
 * Author: 萤火虫
 * E-mail:  Allensuns@163.com
 * Description:
 * CreateTime: 2019-04 -10
 **/
public class BookDetailActivity extends ResouBaseActivity<BookDetailPresenter> implements IBookDetailContract.IBookDetailView, UMShareListener {
    /**
     * 启动详情页面
     *
     * @param context
     * @param bookId  书籍Id
     */
    public static void startDetailActivity(Context context, String bookId) {
        Intent intent = new Intent(context, BookDetailActivity.class);
        intent.putExtra(Constant.EXTRA_BOOK_ID, bookId);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.anim_detail_enter, R.anim.anim_no);
        }
    }

    private static final String TAG = "BookDetailActivity-App";
    @BindView(R.id.ivCover)
    ImageView ivCover;
    @BindView(R.id.tvBookTitle)
    TextView tvBookTitle;
    @BindView(R.id.starRatingBar)
    StarRatingBar starRatingBar;
    @BindView(R.id.tvStarCount)
    TextView tvStarCount;
    @BindView(R.id.tvAuthor)
    TextView tvAuthor;
    @BindView(R.id.tvWordNum)
    TextView tvWordNum;
    @BindView(R.id.tvPay)
    TextView tvPay;
    @BindView(R.id.tv_open_vip)
    TextView tvOpenVip;
    @BindView(R.id.tvCollectNum)
    TextView tvCollectNum;
    @BindView(R.id.tvReadNum)
    TextView tvReadNum;
    @BindView(R.id.tvComNum)
    TextView tvComNum;
    @BindView(R.id.desc_text)
    ExpandableTextView descText;
    @BindView(R.id.tvNew)
    TextView tvNew;
    @BindView(R.id.tvChapterName)
    TextView tvChapterName;
    @BindView(R.id.mScrollView)
    ScrollView mScrollView;
    @BindView(R.id.tvChapterState)
    TextView tvChapterState;
    @BindView(R.id.rlNewChapter)
    RelativeLayout rlNewChapter;
    @BindView(R.id.tvCategory)
    TextView tvCategory;
    @BindView(R.id.tvChapterNum)
    TextView tvChapterNum;
    @BindView(R.id.ivGo)
    ImageView ivGo;
    @BindView(R.id.rlCategory)
    RelativeLayout rlCategory;
    @BindView(R.id.add_to_book_shelf_text)
    TextView addToBookShelfText;
    @BindView(R.id.start_read_text)
    TextView startReadText;
    @BindView(R.id.cvDetail)
    BookDetailCommentView cvDetail;
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_share)
    ImageView titleShare;
    @BindView(R.id.cvDetailRec)
    BookDetailRecomView cvDetailRec;
    @BindView(R.id.tvState)
    TextView tvState;
    @BindView(R.id.tvBookCategory_ll)
    LinearLayout tvBookCategory_ll;
    @BindView(R.id.tvBookCategory)
    TextView tvBookCategory;
    @BindView(R.id.llpay)
    LinearLayout llpay;

    boolean isCliable = true;
    private String mBookId, novelName;

    @Override
    public void initData() {
        mPresenter.init(mBookId);
    }

    @Override
    public void showContent() {
        dissLoading();
    }

    @Override
    public void showProgress() {
        showLoading();
    }

    @Override
    public void showError(Throwable throwable) {
        dissLoading();
        ToastUtil.makeShortToast("网络异常");
        titleShare.setVisibility(View.GONE);
        showNetErrorView(R.id.rlContent);
    }

    @Override
    public void showEmpty() {

    }

    @Override
    protected void initStatusBar() {

    }

    @Override
    protected void initPresenter() {
        if (mPresenter == null) {
            mPresenter = new BookDetailPresenter(this, mBookId);
        }
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        mBookId = getIntent().getStringExtra(Constant.EXTRA_BOOK_ID);
        cvDetail.setCommentOnclickListener(new OnCommentOnclickListener() {
            @Override
            public void commentCallback() {
                ReleaseCommentActivity.start(BookDetailActivity.this, mBookId);

            }

            @Override
            public void lookAllComment() {
                CommentListActivity.start(BookDetailActivity.this, mBookId, novelName);
            }

            @Override
            public void commentOnclickListener(String commentId) {
                CommentDetailActivity.start(BookDetailActivity.this, mBookId, commentId);
            }
        });
        cvDetailRec.setOnClickListener(new BookDetailRecomView.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isNetwork()) {
                    mPresenter.getTypeList();
                }
            }
        });
        /**
         * 防止首次进入该页面 没有到顶部
         */
        mScrollView.smoothScrollTo(0, 20);
        ivCover.setFocusable(true);
        ivCover.setFocusableInTouchMode(true);
        ivCover.requestFocus();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_book_detail;
    }

    @Override
    public void retryRefreshData() {
        mPresenter.init(mBookId);
    }

    UnShelfFragment unShelfFragment = null;

    @Override
    public void initViewData(List<Object> list) {
        titleShare.setVisibility(View.VISIBLE);
        BookDetailBean detailBean = (BookDetailBean) list.get(0);
        if (detailBean != null) {
            if (detailBean.getUnshelf().equals("1")) {
                mScrollView.setVisibility(View.GONE);
                titleShare.setVisibility(View.GONE);
                if (unShelfFragment == null) {
                    unShelfFragment = new UnShelfFragment(new NetErrorFragment.OnClick() {
                        @Override
                        public void onClick() {
                            Intent intent = new Intent(BookDetailActivity.this, MainActivity.class);
                            intent.putExtra("index", 1);
                            startActivity(intent);
                            finish();
                        }
                    });
                }
                unShelfFragment.show(R.id.rlContent, getSupportFragmentManager());
                return;
            }
            Glide.with(this).applyDefaultRequestOptions(new RequestOptions()
                    .format(DecodeFormat.PREFER_RGB_565)
                    .placeholder(R.mipmap.ic_place)
                    .error(R.mipmap.ic_place))
                    .load(detailBean.getCoverUrl() == null ? "" : detailBean.getCoverUrl())
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(ivCover);
            tvBookTitle.setText(detailBean.getNovelName());
            novelName = detailBean.getNovelName();
            starRatingBar.setStarMark(10);
            starRatingBar.setIsClickable(false);
            tvPay.setText(detailBean.getBookSlogan() + "");
            if (UserInstance.getLoginData().getIsVipUser() == 1) {
                tvOpenVip.setText("续费>");
            } else {
                tvOpenVip.setText("开通>");
            }

            int num = (int) (1 + Math.random() * (100 - 1 + 1));
            tvStarCount.setText(String.format(getString(R.string.text_star_count), "10", String.valueOf(num)));
            tvAuthor.setText(detailBean.getAuthorName());
            String wordNum = String.valueOf(Math.round(detailBean.getTotalWord() / 10000) + getString(R.string.character_unit));
            Log.i("字数", "initViewData: " + detailBean.getTotalWord() / 10000);
            int state = detailBean.getSerialStatus();
            String bookState = "";
            if (state == 1) {
                bookState = "连载";
            } else if (state == 2) {
                bookState = "暂停";
            } else if (state == 3) {
                bookState = "已完结";
            }
            if (detailBean.getSloganType() == 0) {
                isCliable = false;
            } else {
                isCliable = true;
            }
            try {
                startReadText.setText(detailBean.getFreeType() == 0 ? "免费阅读" : "开始阅读");
            } catch (Exception e) {
                startReadText.setText("开始阅读");
            }
            tvWordNum.setText(wordNum);
            tvState.setText(bookState);
            tvCollectNum.setText(String.valueOf((int) (1 + Math.random() * (100 - 1 + 1))));
            tvReadNum.setText(String.valueOf((int) (1 + Math.random() * (100 - 1 + 1))));
            tvComNum.setText(String.valueOf((int) (1 + Math.random() * (100 - 1 + 1))));
            descText.setText(detailBean.getNovelDescription());
            tvChapterName.setText(detailBean.getUpdateChapterName());
            tvChapterState.setText(DateUtils.getTheDayFromNow(detailBean.getUpdateTime()));
            tvChapterNum.setText("共" + String.valueOf(detailBean.getChapterNum()) + "章");
            if (!TextUtils.isEmpty(detailBean.getCategoryName())) {
                tvBookCategory_ll.setVisibility(View.VISIBLE);
                tvBookCategory.setText(detailBean.getCategoryName());
            }else
            {
                tvBookCategory_ll.setVisibility(View.GONE);
            }
        }

        BaseComment baseComment = (BaseComment) list.get(1);
        if (baseComment == null || baseComment.getData() == null) {
            cvDetail.setData(null, mBookId, novelName, "0");
        } else {
            List<BaseComment.DataBean> commentBeanlist = baseComment.getData();
            cvDetail.setData(commentBeanlist, mBookId, novelName, baseComment.getDataSize() + "");
        }
        List<TypeBean> typeBeanlist = (List<TypeBean>) list.get(2);
        cvDetailRec.setData(typeBeanlist);
    }

    @Override
    public void refreshAddToShelfBtn(boolean isAdded) {
        if (isAdded) {
            addToBookShelfText.setText(R.string.already_in_book_shelf);
        } else {
            addToBookShelfText.setText(R.string.add_to_book_shelf);
        }
        addToBookShelfText.setClickable(!isAdded);
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @Override
    public void refreshRecyclerItem(List<TypeBean> list) {
        cvDetailRec.setData(list);
    }

    @Override
    public void refreshCommentItem(List<BaseComment.DataBean> list, String total) {
        if (list == null || list.size() == 0) {
            cvDetail.setData(null, mBookId, novelName, "0");
        } else {
            cvDetail.setData(list, mBookId, novelName, total);
        }
    }

    @Override
    public void refreshLike(int count) {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        /**
         * 防止首次进入该页面 没有到顶部
         */
        mScrollView.smoothScrollTo(0, 20);
        ivCover.setFocusable(true);
        ivCover.setFocusableInTouchMode(true);
        ivCover.requestFocus();
        mPresenter.init(intent.getStringExtra(Constant.EXTRA_BOOK_ID));
    }

    long firstTime = 0;

    @OnClick({R.id.add_to_book_shelf_text, R.id.start_read_text, R.id.rlNewChapter, R.id.rlCategory, R.id.llpay, R.id.title_back, R.id.title_share})
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.start_read_text://开始阅读
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime < 2000) {
                    return;
                }
                firstTime = secondTime;
                mPresenter.startToReader(this);
                break;
            case R.id.add_to_book_shelf_text:
                //加入书架
                if (isNetwork()) {
                    mPresenter.addToBookShelf2();
                }
                break;
            case R.id.rlCategory:
                if (isNetwork()) {
                    mPresenter.startCatalogueActivity(this);
                }
                break;
            case R.id.rlNewChapter:
                //最新
                mPresenter.startToReaderLastChapter(this);
                break;
            case R.id.llpay:
                // 会员中心
                /**
                 * 如果时包外书籍且用户是vip不让进去
                 */
                if (isCliable) {
                    VipCenter.start(this);
                }
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.title_share:
                if (isNetwork()) {
                    mPresenter.share(this, this);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_no, R.anim.anim_detail_exit);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void Event(MessageEvent messageEvent) {
        if ("intent_comment".equals(messageEvent.getMessage())) {
            mPresenter.getCommentList();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
        //清空mPresenter里的数据源
        mPresenter.onDestroy();
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {
        switch (share_media) {
            case WEIXIN:
            case WEIXIN_CIRCLE:
                if (!WXUtils.isWeixinAvilible(this)) {
                    ToastUtil.makeShortToast("您未安装微信，请选择其他分享方式");
                    return;
                }
                break;
            case QZONE:
            case QQ:
                if (!WXUtils.isQQClientAvailable(this)) {
                    ToastUtil.makeShortToast("您未安装QQ，请选择其他分享方式");
                    return;
                }
                break;
        }
    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
        SnsPlatform snsPlatform = share_media.toSnsPlatform();
    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {

    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {

    }

    @Override
    protected void onPause() {
        super.onPause();
//        cvDetail.stopViewFilper();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        cvDetail.startViewFilper();
        if (mPresenter != null) {
//            if (sIsAddedBookCollection) {
//                addToBookShelfText.setText(R.string.already_in_book_shelf);
//            } else {
//                addToBookShelfText.setText(R.string.add_to_book_shelf);
//            }
//            addToBookShelfText.setClickable(!sIsAddedBookCollection);
            mPresenter.checkWhetherCollection();
        }
    }

}
